package app.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Restrictions;

import app.entity.User;
import app.utils.HibernateUtil;

public class UserDAO {

	public static boolean auth(String username, String password) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Criteria cr = session.createCriteria(User.class);
		
		Criterion uname = Restrictions.eq("username", username);
		Criterion pwd = Restrictions.eq("password", password);
		
		LogicalExpression andExp = Restrictions.and(uname, pwd);
		cr.add(andExp);
		
		
		@SuppressWarnings("rawtypes")
		List result = cr.list();
		
		if (result.size() == 1) return true;
		
		session.getTransaction().commit();
		
		return false;
	}

	
	public static boolean isExistUsername(String username) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Criteria cr = session.createCriteria(User.class);
		cr.add(Restrictions.eq("username", username));
		@SuppressWarnings("rawtypes")
		List list = cr.list();
		
		if (list.size() == 1) return true;
		session.getTransaction().commit();
		return false;
	}
	
	public static void addNewUser(User user) {
		Session session = HibernateUtil.getSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
	}
	
}
